package com.ybkj.daijia.server.controller;

import com.ybkj.daijia.serverUtils.ExcelUtil;
import com.ybkj.daijia.OrderNumberConfig;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.common.HtmlHelper;
import com.ybkj.daijia.common.PageVo;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.server.event.model.OperationLogEvent;
import com.ybkj.daijia.server.mapper.FinancialRecordMapper;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.mc.PassengerAccount;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverPaymentsRecord;
import com.ybkj.daijia.server.model.FinancialRecord;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverPaymentsRecordService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.FinancialRecordService;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Shine
 */
@Controller
@RequestMapping(value = "financialrecord")
public class FinancialRecordController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private FinancialRecordService financialRecordService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private DriverPaymentsRecordService driverPaymentsRecordService;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Autowired
    private FinancialRecordMapper financialRecordMapper;

    @Autowired
    private DriverService driverService;


    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ModelAndView list(
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "param") String param,
        @RequestParam(required = false, value = "thisbtn") String thisbtn,
        @RequestParam(required = false, value = "ftype") Long ftype,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime) throws ParseException {

        Setting setting = settingUtils.get();

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("financial")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("financial/list");

            Date start = null;
            Date end = null;

            if (StringUtils.isNotBlank(startTime)) {
                try {
                    start = DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            if (StringUtils.isNotBlank(endTime)) {
                try {
                    end = DateUtils.parseDate(endTime, "yyyy-MM-dd HH:mm");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            if (StringUtils.isNotBlank(thisbtn)) {
                Map<String, Date> map = getStartAndEnd(start, end, thisbtn, setting);
                start = map.get("start");
                end = map.get("end");
            }

            if (start != null) {
                startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(start);
            }
            if (end != null) {
                endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(end);
            }

            mv.addObject("companys", companyService.findAll());
            mv.addObject("companyId", companyId);
            mv.addObject("param", param);

            BigDecimal nowMoney = BigDecimal.ZERO;
            String type = "all";
            if (null != ftype && ftype == 1) {
                type = "income";
                mv.addObject("ftype", 1);
            } else if (null != ftype && ftype == 2) {
                type = "expenditure";
                mv.addObject("ftype", 2);
            } else {
                mv.addObject("ftype", 0);
            }
            mv.addObject("page",
                financialRecordService.queryAll(start, end, param, type, companyId, "byOrder"));
            mv.addObject("startTime", startTime);
            mv.addObject("endTime", endTime);

            mv.addObject("nowMoney", nowMoney);
            mv.addObject("thisbtn", thisbtn);
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "listByDriver", method = RequestMethod.GET)
    public ModelAndView listByDriver(
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "param") String param,
        @RequestParam(required = false, value = "thisbtn") String thisbtn,
        @RequestParam(required = false, value = "ftype") Long ftype,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime) throws ParseException {

        Setting setting = settingUtils.get();

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("financial")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("financial/listbydriver");

            Date start = null;
            Date end = null;

            if (StringUtils.isNotBlank(startTime)) {
                try {
                    start = DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            if (StringUtils.isNotBlank(endTime)) {
                try {
                    end = DateUtils.parseDate(endTime, "yyyy-MM-dd HH:mm");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            if (StringUtils.isNotBlank(thisbtn)) {
                Map<String, Date> map = getStartAndEnd(start, end, thisbtn, setting);
                start = map.get("start");
                end = map.get("end");
            }

            if (start != null) {
                startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(start);
            }
            if (end != null) {
                endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(end);
            }

            mv.addObject("companys", companyService.findAll());
            mv.addObject("companyId", companyId);
            mv.addObject("param", param);

            BigDecimal nowMoney = BigDecimal.ZERO;
            String type = "all";
            if (null != ftype && ftype == 1) {
                type = "income";
                mv.addObject("ftype", 1);
            } else if (null != ftype && ftype == 2) {
                type = "expenditure";
                mv.addObject("ftype", 2);
            } else {
                mv.addObject("ftype", 0);
            }
            mv.addObject("page",
                financialRecordService.queryAll(start, end, param, type, companyId, "byDriver"));

            mv.addObject("startTime", startTime);
            mv.addObject("endTime", endTime);

            mv.addObject("nowMoney", nowMoney);
            mv.addObject("thisbtn", thisbtn);
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "driverlist", method = RequestMethod.GET)
    public ModelAndView driverlist(
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "param") String param,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("financial")) {

            Date start = null;
            Date end = null;

            if (StringUtils.isNotBlank(startTime)) {
                try {
                    start = DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            if (StringUtils.isNotBlank(endTime)) {
                try {
                    end = DateUtils.parseDate(endTime, "yyyy-MM-dd HH:mm");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            ModelAndView mv = new ModelAndView();
            mv.setViewName("financial/driverlist");

            mv.addObject("companys", companyService.findAll());
            mv.addObject("page", financialRecordService
                .queryDriver(companyId, param, start, end, Pager.getPage(), Pager.getLimit()));

            mv.addObject("companyId", companyId);
            mv.addObject("param", param);
            mv.addObject("startTime", startTime);
            mv.addObject("endTime", endTime);

            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "memberlist", method = RequestMethod.GET)
    public ModelAndView memberlist(
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "param") String param) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("financial")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("financial/memberlist");

            mv.addObject("companys", companyService.findAll());
            mv.addObject("page", financialRecordService
                .queryMember(companyId, param, Pager.getPage(), Pager.getLimit()));

            mv.addObject("companyId", companyId);
            mv.addObject("param", param);

            return mv;
        } else {
            throw new NoPermissionException();
        }


    }

    @RequestMapping("driverrechargelist")
    public String driverrechargelist(Model model,
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "param") String param,
        @RequestParam(required = false, value = "thisbtn") String thisbtn,
        @RequestParam(required = false, value = "type") String type,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime) throws ParseException {

        Setting setting = settingUtils.get();

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("financial")) {
            Date start = null;
            Date end = null;

            if (StringUtils.isNotBlank(startTime)) {
                try {
                    start = DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            if (StringUtils.isNotBlank(endTime)) {
                try {
                    end = DateUtils.parseDate(endTime, "yyyy-MM-dd HH:mm");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            if (StringUtils.isNotBlank(thisbtn)) {
                Map<String, Date> map = getStartAndEnd(start, end, thisbtn, setting);
                start = map.get("start");
                end = map.get("end");
            }

            if (start != null) {
                startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(start);
            }
            if (end != null) {
                endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(end);
            }

            model.addAttribute("companys", companyService.findAll());
            model.addAttribute("page", financialRecordService
                .queryDriverRecharge(companyId, param, type, start, end, Pager.getPage(),
                    Pager.getLimit()));

            model.addAttribute("companyId", companyId);
            model.addAttribute("param", param);
            model.addAttribute("type", type);
            model.addAttribute("thisbtn", thisbtn);
            model.addAttribute("startTime", startTime);
            model.addAttribute("endTime", endTime);

            return "financial/driverrechargelist";
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping("memberrechargelist")
    public String memberrechargelist(Model model,
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "param") String param,
        @RequestParam(required = false, value = "thisbtn") String thisbtn,
        @RequestParam(required = false, value = "type") String type,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime) throws ParseException {

        Subject subject = SecurityUtils.getSubject();
        Setting setting = settingUtils.get();

        if (subject.isPermitted("financial")) {
            Date start = null;
            Date end = null;

            if (StringUtils.isNotBlank(startTime)) {
                try {
                    start = DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            if (StringUtils.isNotBlank(endTime)) {
                try {
                    end = DateUtils.parseDate(endTime, "yyyy-MM-dd HH:mm");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            if (StringUtils.isNotBlank(thisbtn)) {
                Map<String, Date> map = getStartAndEnd(start, end, thisbtn, setting);
                start = map.get("start");
                end = map.get("end");
            }
            if (start != null) {
                startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(start);
            }
            if (end != null) {
                endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(end);
            }

            model.addAttribute("companys", companyService.findAll());
            model.addAttribute("page",
                financialRecordService.queryMemberRecharge(companyId, param, type, start, end));

            model.addAttribute("companyId", companyId);
            model.addAttribute("param", param);
            model.addAttribute("type", type);
            model.addAttribute("startTime", startTime);
            model.addAttribute("endTime", endTime);
            model.addAttribute("thisbtn", thisbtn);
            return "financial/memberrechargelist";
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public ModelAndView add() {

        Subject subject = SecurityUtils.getSubject();
        Setting setting = settingUtils.get();
        String webUrl = setting.getWebUrl() + "/financialrecord/list";
        String referer = request.getHeader("Referer");
        if (subject.isPermitted("financialadd")) {

            ModelAndView mv = new ModelAndView();
            if (!webUrl.equals(referer)) {
                mv.setViewName("500");
                return mv;
            }
            mv.setViewName("financial/add");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    public String create(FinancialRecord financialRecord) {

        Subject subject = SecurityUtils.getSubject();
        Setting setting = settingUtils.get();
        String webUrl = setting.getWebUrl() + "/financialrecord/add";
        String referer = request.getHeader("Referer");
        if (subject.isPermitted("financialadd")) {
            if (!webUrl.equals(referer)) {
                return "500";
            }
            if (financialRecord.getMoney().intValue() != 0) {
                Subject currentUser = SecurityUtils.getSubject();
                Principal principal = (Principal) currentUser.getPrincipal();

                Company company = companyService.findOne(principal.getCompanyId());

                DateFormat format = new SimpleDateFormat("yyyyMMdd");
                StringBuilder sb = new StringBuilder();
                sb.append(OrderNumberConfig.FINANCIAL_RENGONG);//人工添加
                sb.append(OrderNumberConfig.FINANCIAL_WHO_RENGONG);//对象 人工添加
                sb.append(format.format(new Date()));//年月日时间
                sb.append(
                    OrderNumberConfig.padZero(financialRecordService.getRunningNumber() + 1));//流水号
                financialRecord.setCode(sb.toString());

                financialRecord.setCompanyId(company.getId());
                financialRecord.setCompanyName(company.getAbbreviation());
                financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_WAIT);

                financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_RENGONG);

                financialRecordService.save(financialRecord);

                String detail =
                    "【%s】新增了财务记录【" + financialRecord.getMemo() + "】，金额：" + financialRecord
                        .getMoney() + "";
                OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);

            }

            return "redirect:list";
        } else {
            throw new NoPermissionException();
        }
    }

    //审核 财务记录$$$ 和提现没关系
    @RequestMapping(value = "audit", method = RequestMethod.POST)
    public synchronized
    @ResponseBody
    Result<FinancialRecord> audit(Long id, BigDecimal money) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        Setting setting = settingUtils.get();
//        String webUrl = setting.getWebUrl()+"/financialrecord/list";
//        String referer = request.getHeader("Referer");
        if (subject.isPermitted("financialaudit")) {
            Result<FinancialRecord> result = new Result<FinancialRecord>();

//            if(!webUrl.equals(referer)){
//                result.setMessage("禁止CRSF攻击");
//                return result;
//            }

            FinancialRecord financialRecord = financialRecordService.findOne(id);

            if (financialRecord.getType().equals(FinancialRecord.FINANCIALRECORD_TYPE_BAOXIAO)) {
                if (money.doubleValue() >= 0) {
                    result.setMessage("报销金额必须小于0");
                    return result;
                }
            }

            if (financialRecord.getStatus().equals(FinancialRecord.FINANCIALRECORD_OK)) {
                result.setMessage("该财务记录已审核");
                return result;
            }

            financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
            financialRecord.setMoney(money);
            result = financialRecordService.audit(financialRecord);

            if (result.isSuccess()) {
                String detail =
                    "【%s】审核了财务记录【" + financialRecord.getMemo() + "】，金额：" + financialRecord
                        .getMoney() + "";
                OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);
            }

            return result;

        } else {
            throw new NoPermissionException();
        }


    }

    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public
    @ResponseBody
    Result<Integer> delete(Long id, HttpServletRequest req) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        Setting setting = settingUtils.get();
//        String webUrl = setting.getWebUrl()+"/financialrecord/list";
//        String referer = request.getHeader("Referer");
        if (subject.isPermitted("financialdelete")) {
            Result<Integer> result = new Result<Integer>();
//            if(!webUrl.equals(referer)){
//                result.setMessage("禁止CRSF攻击");
//                return result;
//            }
            if (null != id) {
                FinancialRecord financialRecord = financialRecordService.findOne(id);
                if (null != financialRecord) {
                    String detail =
                        "【%s】删除了财务记录【" + financialRecord.getMemo() + "】，金额：" + financialRecord
                            .getMoney() + "";

                    int count = financialRecordService.delete(financialRecord);
                    if (count > 0) {
                        OperationLogEvent operationLogEvent = new OperationLogEvent(principal,
                            detail);
                        applicationEventMulticaster.multicastEvent(operationLogEvent);

                        result.setSuccess(true);
                        result.setMessage("删除成功");
                    } else {
                        result.setMessage("删除失败");
                    }

                } else {
                    result.setMessage("没有可以删除的数据");
                }
            } else {
                result.setMessage("没有可以删除的数据");
            }

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    @org.springframework.web.bind.annotation.InitBinder
    public void InitBinder(WebDataBinder dataBinder) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

    }

    //导出财务明细
    @RequestMapping(value = "exportList", method = RequestMethod.GET)
    public void exportList(
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "param") String param,
        @RequestParam(required = false, value = "thisbtn") String thisbtn,
        @RequestParam(required = false, value = "ftype") Long ftype,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime,
        HttpServletRequest req, HttpServletResponse response) throws IOException, ParseException {
        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("financial")) {
            Date start = null;
            Date end = null;
            Setting setting = settingUtils.get();
            if (StringUtils.isNotBlank(endTime)) {
                end = DateUtils.parseDate(endTime, "yyyy-MM-dd HH:mm");
            }

            if (StringUtils.isNotBlank(startTime)) {
                start = DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm");
            }
            if (StringUtils.isNotBlank(thisbtn)) {
                Map<String, Date> map = getStartAndEnd(start, end, thisbtn, setting);
                start = map.get("start");
                end = map.get("end");
            }
            if (start != null) {
                startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(start);
            }
            if (end != null) {
                endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(end);
            }
            Principal principal = (Principal) subject.getPrincipal();

            String likeParam = null;
            if (StringUtils.isNotBlank(param)) {
                likeParam = "%" + param + "%";
            }
            String type = "all";
            if (null != ftype && ftype == 1) {
                type = "income";
            } else if (null != ftype && ftype == 2) {
                type = "expenditure";
            }
            List<FinancialRecord> content = new ArrayList<FinancialRecord>();
            if (!principal.isCompanyType()) {
                content = financialRecordMapper
                    .selectByCompanyWithParamAndDate(principal.getCompanyId(), likeParam, type,
                        start, end, null, null, "byOrder");
            } else {
                if (null != companyId) {
                    content = financialRecordMapper
                        .selectByCompanyWithParamAndDate(companyId, likeParam, type, start, end,
                            null, null, "byOrder");
                } else {
                    content = financialRecordMapper
                        .selectByCompanyWithParamAndDate(null, likeParam, type, start, end, null,
                            null, "byOrder");
                }
            }
            List<List<String>> rowlist = new ArrayList<List<String>>();
            String heards[] = {"状态", "流水号", "金额", "对象", "公司", "时间", "备注"};
            for (FinancialRecord f : content) {

                List<String> celllist = new ArrayList<String>();

                if (f.getStatus() == 1) {
                    celllist.add("已审");
                } else {
                    celllist.add("待审");
                }
                if (StringUtils.isBlank(f.getCode())) {
                    celllist.add("");
                } else {
                    celllist.add(f.getCode());
                }

                celllist.add(f.getMoney().toString());
                celllist.add(f.getWho());
                celllist.add(f.getOrderCompanyName());
                celllist.add(new SimpleDateFormat("yyyy/MM/dd HH:mm").format(f.getCreated()));

                if (StringUtils.isNotBlank(f.getMemo())) {
                    celllist.add(HtmlHelper.html2Text(f.getMemo()));
                } else {
                    celllist.add("");
                }

                rowlist.add(celllist);

            }

            ExcelUtil.export(req, response, heards, rowlist);
        } else {
            throw new NoPermissionException();
        }
    }

    //导出财务明细
    @RequestMapping(value = "exportListByDriver", method = RequestMethod.GET)
    public void exportListByDriver(
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "param") String param,
        @RequestParam(required = false, value = "thisbtn") String thisbtn,
        @RequestParam(required = false, value = "ftype") Long ftype,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime,
        HttpServletRequest req, HttpServletResponse response) throws IOException, ParseException {
        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("financial")) {
            Date start = null;
            Date end = null;
            Setting setting = settingUtils.get();
            if (StringUtils.isNotBlank(endTime)) {
                end = DateUtils.parseDate(endTime, "yyyy-MM-dd HH:mm");
            }

            if (StringUtils.isNotBlank(startTime)) {
                start = DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm");
            }
            if (StringUtils.isNotBlank(thisbtn)) {
                Map<String, Date> map = getStartAndEnd(start, end, thisbtn, setting);
                start = map.get("start");
                end = map.get("end");
            }
            if (start != null) {
                startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(start);
            }
            if (end != null) {
                endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(end);
            }
            Principal principal = (Principal) subject.getPrincipal();

            String likeParam = null;
            if (StringUtils.isNotBlank(param)) {
                likeParam = "%" + param + "%";
            }
            String type = "all";
            if (null != ftype && ftype == 1) {
                type = "income";
            } else if (null != ftype && ftype == 2) {
                type = "expenditure";
            }
            List<FinancialRecord> content = new ArrayList<FinancialRecord>();
            if (!principal.isCompanyType()) {
                content = financialRecordMapper
                    .selectByCompanyWithParamAndDate(principal.getCompanyId(), likeParam, type,
                        start, end, null, null, "byDriver");
            } else {
                if (null != companyId) {
                    content = financialRecordMapper
                        .selectByCompanyWithParamAndDate(companyId, likeParam, type, start, end,
                            null, null, "byDriver");
                } else {
                    content = financialRecordMapper
                        .selectByCompanyWithParamAndDate(null, likeParam, type, start, end, null,
                            null, "byDriver");
                }
            }
            List<List<String>> rowlist = new ArrayList<List<String>>();
            String heards[] = {"状态", "流水号", "金额", "对象", "公司", "时间", "备注"};
            for (FinancialRecord f : content) {

                List<String> celllist = new ArrayList<String>();

                if (f.getStatus() == 1) {
                    celllist.add("已审");
                } else {
                    celllist.add("待审");
                }
                if (StringUtils.isBlank(f.getCode())) {
                    celllist.add("");
                } else {
                    celllist.add(f.getCode());
                }

                celllist.add(f.getMoney().toString());
                celllist.add(f.getWho());
                celllist.add(f.getCompanyName());
                celllist.add(new SimpleDateFormat("yyyy/MM/dd HH:mm").format(f.getCreated()));

                if (StringUtils.isNotBlank(f.getMemo())) {
                    celllist.add(HtmlHelper.html2Text(f.getMemo()));
                } else {
                    celllist.add("");
                }

                rowlist.add(celllist);

            }

            ExcelUtil.export(req, response, heards, rowlist);
        } else {
            throw new NoPermissionException();
        }
    }

    //导出客户充值记录
    @RequestMapping(value = "exportMemberRechargelist", method = RequestMethod.GET)
    public void exportMemberRechargelist(
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "param") String param,
        @RequestParam(required = false, value = "thisbtn") String thisbtn,
        @RequestParam(required = false, value = "type") String type,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime,
        HttpServletRequest req, HttpServletResponse response) throws IOException, ParseException {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("financial")) {
            Date start = null;
            Date end = null;
            Setting setting = settingUtils.get();
            if (StringUtils.isNotBlank(endTime)) {
                end = DateUtils.parseDate(endTime, "yyyy-MM-dd HH:mm");
            }

            if (StringUtils.isNotBlank(startTime)) {
                start = DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm");
            }
            if (StringUtils.isNotBlank(thisbtn)) {
                Map<String, Date> map = getStartAndEnd(start, end, thisbtn, setting);
                start = map.get("start");
                end = map.get("end");
            }
            if (start != null) {
                startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(start);
            }
            if (end != null) {
                endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(end);
            }
            Subject currentUser = SecurityUtils.getSubject();
            Principal principal = (Principal) currentUser.getPrincipal();

            Map<String, Object> params = new HashMap<String, Object>();
            if (!principal.isCompanyType()) {
                params.put("companyId", principal.getCompanyId());
            } else {
                if (null != companyId) {
                    params.put("companyId", companyId);
                }
            }
            if (StringUtils.isBlank(type)) {
                type = null;
            }

            params.put("type", type);
            String likeName = null;
            if (StringUtils.isNotBlank(param)) {
                likeName = "%" + param + "%";
                params.put("likeName", likeName);
            }
            if (null != start) {
                params.put("start", start);
            }
            if (null != end) {
                params.put("end", end);
            }

            PageVo<PassengerAccount> page = financialRecordService
                .exprotMemberRecharge(companyId, param, type, start, end);

            List<List<String>> rowlist = new ArrayList<List<String>>();
            String heards[] = {"客户名称", "客户手机号", "充值时间", "金额(元)", "充值后余额(元)", "充值方式", "操作人", "备注"};
            for (PassengerAccount passengerAccount : page.getContent()) {

                List<String> celllist = new ArrayList<String>();

                celllist.add(passengerAccount.getPassenger_name());

                celllist.add(passengerAccount.getPassenger_phone());

                celllist.add(
                    new SimpleDateFormat("yyyy-MM-dd HH:mm").format(passengerAccount.getCreated()));

                celllist.add(new BigDecimal(passengerAccount.getMoney())
                    .setScale(2, BigDecimal.ROUND_HALF_UP).toString());

                celllist.add(new BigDecimal(passengerAccount.getAfterDrawMoney())
                    .setScale(2, BigDecimal.ROUND_HALF_UP).toString());

                celllist.add(passengerAccount.getPayTypeStr());

                celllist.add(passengerAccount.getOperator());

                celllist.add(passengerAccount.getDetails());

                rowlist.add(celllist);

            }
            ExcelUtil.export(req, response, heards, rowlist);
        } else {
            throw new NoPermissionException();
        }

    }

    //导出司机充值记录
    @RequestMapping(value = "exportDriverRechargelist", method = RequestMethod.GET)
    public void exportDriverRechargelist(
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "param") String param,
        @RequestParam(required = false, value = "thisbtn") String thisbtn,
        @RequestParam(required = false, value = "type") String type,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime,
        HttpServletRequest req, HttpServletResponse response) throws IOException, ParseException {

        Subject subject = SecurityUtils.getSubject();

        Setting setting = settingUtils.get();

        if (subject.isPermitted("financial")) {
            Date start = null;
            Date end = null;
            if (StringUtils.isNotBlank(startTime)) {
                Calendar c2 = Calendar.getInstance();
                c2.setTime(DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm"));
                c2.set(Calendar.HOUR_OF_DAY, setting.getWorkBegin());
                c2.set(Calendar.MINUTE, 0);
                c2.set(Calendar.SECOND, 0);
                c2.set(Calendar.MILLISECOND, 0);
                start = c2.getTime();
            }
            if (StringUtils.isNotBlank(endTime)) {
                end = DateUtils.parseDate(endTime, "yyyy-MM-dd HH:mm");
            }

            if (StringUtils.isNotBlank(startTime)) {
                start = DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm");
            }
            if (StringUtils.isNotBlank(thisbtn)) {
                Map<String, Date> map = getStartAndEnd(start, end, thisbtn, setting);
                start = map.get("start");
                end = map.get("end");
            }
            if (start != null) {
                startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(start);
            }
            if (end != null) {
                endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(end);
            }

            PageVo<DriverPaymentsRecord> pageVo = financialRecordService
                .queryDriverRecharge(companyId, param, type, start, end, null, null);
            List<DriverPaymentsRecord> content = pageVo.getContent();

            List<List<String>> rowlist = new ArrayList<List<String>>();
            String heards[] = {"服务人员姓名", "服务人员电话", "时间", "金额(元)", "操作后余额(元)", "方式", "操作人", "备注"};
            if (!CollectionUtils.isEmpty(content)) {
                for (DriverPaymentsRecord d : content) {

                    List<String> celllist = new ArrayList<String>();

                    celllist.add(d.getDriverRealName());

                    celllist.add(d.getDriverPhone());

                    celllist.add(new SimpleDateFormat("yyyy-MM-dd").format(d.getHappend()));

                    celllist.add(d.getMoney().toString());

                    celllist.add(d.getAfterMoney().toString());

                    celllist.add(d.getRecordTypeStr());

                    celllist.add(d.getOperating());

                    if (StringUtils.isNotBlank(d.getMemo())) {
                        celllist.add(HtmlHelper.html2Text(d.getMemo()));
                    } else {
                        celllist.add("");
                    }

                    rowlist.add(celllist);
                }
            }

            ExcelUtil.export(req, response, heards, rowlist);
        } else {
            throw new NoPermissionException();
        }
    }

    //导出司机预存款
    @RequestMapping(value = "exportDriver", method = RequestMethod.GET)
    public void exportDriver(
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "param") String param,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime,
        HttpServletRequest req, HttpServletResponse response) throws IOException {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("financial")) {

            Date start = null;
            Date end = null;

            if (StringUtils.isNotBlank(startTime)) {
                try {
                    start = DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            if (StringUtils.isNotBlank(endTime)) {
                try {
                    end = DateUtils.parseDate(endTime, "yyyy-MM-dd HH:mm");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            PageVo<Driver> pageVo = financialRecordService
                .queryDriver(companyId, param, start, end, null, null);

            List<List<String>> rowlist = new ArrayList<List<String>>();
            String heards[] = {"姓名", "账户", "手机号", "总预存款", "余额"};

            List<Driver> content = pageVo.getContent();
            if (!CollectionUtils.isEmpty(content)) {
                for (Driver d : content) {

                    List<String> celllist = new ArrayList<String>();

                    if (StringUtils.isBlank(d.getRealname())) {
                        celllist.add("");
                    } else {
                        celllist.add(d.getRealname());
                    }

                    if (StringUtils.isBlank(d.getUsername())) {
                        celllist.add("");
                    } else {
                        celllist.add(d.getUsername());
                    }

                    if (StringUtils.isBlank(d.getPhone())) {
                        celllist.add("");
                    } else {
                        celllist.add(d.getPhone());
                    }

                    if (d.getAdvance() == null) {
                        celllist.add(BigDecimal.ZERO.toString());
                    } else {
                        celllist.add(d.getAdvance().toString());
                    }

                    if (d.getVirtual() == null) {
                        celllist.add(BigDecimal.ZERO.toString());
                    } else {
                        celllist.add(d.getVirtual().toString());
                    }

                    rowlist.add(celllist);

                }
            }

            ExcelUtil.export(req, response, heards, rowlist);
        } else {
            throw new NoPermissionException();
        }


    }


    //导出客户预存款
    @RequestMapping(value = "exportMember", method = RequestMethod.GET)
    public void exportMember(
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "param") String param,
        HttpServletRequest req, HttpServletResponse response) throws IOException {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("financial")) {

            PageVo<Passenger> page = financialRecordService
                .queryMember(companyId, param, null, null);

            List<Passenger> passengers = page.getContent();

            List<List<String>> rowlist = new ArrayList<List<String>>();
            String heards[] = {"姓名", "手机号", "总预存款", "余额"};
            for (Passenger p : passengers) {

                List<String> celllist = new ArrayList<String>();

                if (StringUtils.isBlank(p.getName())) {
                    celllist.add("");
                } else {
                    celllist.add(p.getName());
                }

                celllist.add(p.getPhone());

                if (p.getAdvance() == null) {
                    celllist.add(BigDecimal.ZERO.toString());
                } else {
                    celllist.add(p.getAdvance().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                }

                if (p.getDrawMoney() == null) {
                    celllist.add(BigDecimal.ZERO.toString());
                } else {
                    celllist.add(p.getDrawMoney().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                }

                rowlist.add(celllist);

            }

            ExcelUtil.export(req, response, heards, rowlist);
        } else {
            throw new NoPermissionException();
        }


    }

    //导出
    @RequestMapping(value = "financialExport", method = RequestMethod.POST)
    public void financialExport(
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "param") String param,
        @RequestParam(required = false, value = "thisbtn") String thisbtn,
        @RequestParam(required = false, value = "ftype") Long ftype,
        @RequestParam(required = false, value = "endTime") String endTime,
        @RequestParam(required = false, value = "startTime") String startTime,
        HttpServletRequest req, HttpServletResponse response
    ) throws IOException {

    }

    private Map<String, Date> getStartAndEnd(Date start, Date end, String thisbtn,
        Setting setting) {

        Map<String, Date> map = new HashMap<String, Date>();

        Calendar nowCalendar = Calendar.getInstance();
        int nowHour = nowCalendar.get(Calendar.HOUR_OF_DAY);
        if (StringUtils.isNotBlank(thisbtn)) {
            Calendar calendar = Calendar.getInstance();
            if ("thisYearTotal".equals(thisbtn)) {    //本年的所有记录
                calendar.setTime(new Date());
                calendar.set(Calendar.MONTH, 0);
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                calendar.set(Calendar.HOUR_OF_DAY, setting.getWorkBegin());
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                start = calendar.getTime();
                calendar.add(Calendar.YEAR, 1);
                calendar.add(Calendar.DAY_OF_MONTH, -1);
                calendar.add(Calendar.HOUR, 23);
                calendar.add(Calendar.MINUTE, 59);
                calendar.add(Calendar.SECOND, 59);
                end = calendar.getTime();
                if (setting.getWorkBegin() < nowHour) {
                    calendar.add(Calendar.HOUR, -23);
                    calendar.add(Calendar.MINUTE, -59);
                    calendar.add(Calendar.SECOND, -59);
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                    calendar.add(Calendar.YEAR, -1);
                    start = calendar.getTime();
                    calendar.add(Calendar.HOUR, 23);
                    calendar.add(Calendar.MINUTE, 59);
                    calendar.add(Calendar.SECOND, 59);
                    calendar.add(Calendar.DAY_OF_MONTH, -1);
                    calendar.add(Calendar.YEAR, 1);
                    end = calendar.getTime();
                }
            } else if ("thisMonthTotal".equals(thisbtn)) {//本月的所有记录
                calendar.setTime(new Date());
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                calendar.set(Calendar.HOUR_OF_DAY, setting.getWorkBegin());
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                start = calendar.getTime();
                calendar.add(Calendar.MONTH, 1);
                calendar.add(Calendar.DAY_OF_MONTH, -1);
                calendar.add(Calendar.HOUR, 23);
                calendar.add(Calendar.MINUTE, 59);
                calendar.add(Calendar.SECOND, 59);
                end = calendar.getTime();
                if (setting.getWorkBegin() < nowHour) {
                    calendar.add(Calendar.HOUR, -23);
                    calendar.add(Calendar.MINUTE, -59);
                    calendar.add(Calendar.SECOND, -59);
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                    calendar.add(Calendar.MONTH, -1);
                    start = calendar.getTime();
                    calendar.add(Calendar.HOUR, 23);
                    calendar.add(Calendar.MINUTE, 59);
                    calendar.add(Calendar.SECOND, 59);
                    calendar.add(Calendar.MONTH, 1);
                    calendar.add(Calendar.DAY_OF_MONTH, -1);
                    end = calendar.getTime();
                }
            } else if ("lastDayTotal".equals(thisbtn)) {    //昨天的所有记录
                calendar.setTime(new Date());
                calendar.set(Calendar.HOUR_OF_DAY, setting.getWorkBegin());
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                calendar.add(Calendar.DAY_OF_MONTH, -1);
                start = calendar.getTime();
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                calendar.add(Calendar.SECOND, -1);
                end = calendar.getTime();
                if (setting.getWorkBegin() > nowHour) {
                    calendar.add(Calendar.SECOND, 1);
                    calendar.add(Calendar.DAY_OF_MONTH, -2);
                    start = calendar.getTime();
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                    calendar.add(Calendar.SECOND, -1);
                    end = calendar.getTime();
                }
            } else if ("thisDayTotal".equals(thisbtn)) {    //今天的所有记录
                calendar.setTime(new Date());
                calendar.set(Calendar.HOUR_OF_DAY, setting.getWorkBegin());
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                calendar.add(Calendar.DAY_OF_MONTH, -1);
                start = calendar.getTime();
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                calendar.add(Calendar.SECOND, -1);
                end = calendar.getTime();
                if (setting.getWorkBegin() > nowHour) {
                    calendar.add(Calendar.SECOND, 1);
                    calendar.add(Calendar.DAY_OF_MONTH, -2);
                    start = calendar.getTime();
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                    calendar.add(Calendar.SECOND, -1);
                    end = calendar.getTime();
                }
                calendar.setTime(end);
                calendar.add(Calendar.SECOND, 1);
                start = calendar.getTime();
                calendar.setTime(start);
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                calendar.add(Calendar.SECOND, -1);
                end = calendar.getTime();
            } else if ("allTotal".equals(thisbtn)) {

            }

        }
        ArrayList<Date> list = new ArrayList<Date>();
        map.put("start", start);
        map.put("end", end);
        return map;
    }

}
